package own.stu.bytebuffer.sim.agent.configDynamic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.yaml.snakeyaml.Yaml;
import own.stu.bytebuffer.sim.agent.Cached;
import own.stu.bytebuffer.sim.agent.util.SimHttpClient;

import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NacosConfigManagerV2 {

    private String serverAddr;
    private String dataId;
    private String group;
    private String nameSpaceId = "69c4eecb-05bd-4041-81fe-1473f95f578c";

    public NacosConfigManagerV2(String serverAddr, String dataId, String group) {
        this.serverAddr = serverAddr;
        this.dataId = dataId;
        this.group = group;
        init();
    }

    static ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);

    public String getUrl() {
        String url = "http://" + serverAddr + "/nacos/v2/cs/config?dataId=" + dataId + "&group=" + group + "&namespaceId=" + nameSpaceId + "&username=nacos&password=nacos";
        return url;
    }


    private void init() {
        // TODO 1 -> 30
        scheduledThreadPoolExecutor.scheduleAtFixedRate(new Task(), 10, 1 * 60, TimeUnit.SECONDS);
    }

    private class Task implements Runnable {

        @Override
        public void run() {
            try {

                String body = SimHttpClient.httpGet(getUrl());
                JSONObject jsonObject = JSON.parseObject(body);
                if(jsonObject != null){
                    Object data = jsonObject.get("data");
                    if(data != null){
                        String info = getInfo((String) data);
                        Cached.setLevel(Integer.valueOf(info));
                    }
                }
            } catch (Exception e) {
                System.out.println("get config info from nacos " + e.getMessage());
            }
        }
    }

    public static void main(String[] args) throws Exception {
        NacosConfigManagerV2 configManager = new NacosConfigManagerV2("127.0.0.1:8848", "frame-config.yaml", "DEFAULT_GROUP");
        String body = SimHttpClient.httpGet(configManager.getUrl());
//        System.out.println(body);
        JSONObject jsonObject = JSON.parseObject(body);
        if(jsonObject != null){
            Object data = jsonObject.get("data");
            if(data != null){
                getInfo((String) data);
            }
        }
//        System.out.println("Initial config: " + config);
//        getInfo(config);

    }

    private static String getInfo(String configData) {
        // 使用SnakeYAML解析YAML配置
        Yaml yaml = new Yaml();
        Map<String, Object> yamlConfig = yaml.load(configData);
        Object o = yamlConfig.get("agent.level");
        System.out.println("agl : " + o); // TODO del
        if (o == null) {
            return ""; // default v
        }
        if (o instanceof Integer) {
            return o + "";
        }
        return (String) o;
    }

   /* static volatile boolean stop = false;

    Thread nacosInfo = new Thread(() -> {
        while(!stop){

        }
    });*/

    static {
        Runnable shutdownHook = () -> scheduledThreadPoolExecutor.shutdown();
        // 注册钩子
        addShutdownHook(shutdownHook);
    }

    static void addShutdownHook(Runnable hook) {
        Runtime.getRuntime().addShutdownHook(new Thread(hook));
    }
}
